package cn.com.pajx.pajx_visitor_v3.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.telpo.scan.ScanCallBack;
import com.telpo.scan.ScanTool;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedHashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.pajx.pajx_visitor_v3.R;
import cn.com.pajx.pajx_visitor_v3.api.Api;
import cn.com.pajx.pajx_visitor_v3.base.BaseMvpActivity;
import cn.com.pajx.pajx_visitor_v3.bean.EventMessage;
import cn.com.pajx.pajx_visitor_v3.bean.MainVisiteBean;
import cn.com.pajx.pajx_visitor_v3.broadcast.AlarmTaskReceiver;
import cn.com.pajx.pajx_visitor_v3.face.FaceNIRActivity;
import cn.com.pajx.pajx_visitor_v3.mvp.presenter.LoadDataPresenterImpl;
import cn.com.pajx.pajx_visitor_v3.service.AlarmService;
import cn.com.pajx.pajx_visitor_v3.ui.fragment.BindSchoolFragment;
import cn.com.pajx.pajx_visitor_v3.ui.fragment.VisitorInfoFragment;
import cn.com.pajx.pajx_visitor_v3.utils.ActivityManagerUtil;
import cn.com.pajx.pajx_visitor_v3.utils.AppConstant;
import cn.com.pajx.pajx_visitor_v3.utils.LogUtils;
import cn.com.pajx.pajx_visitor_v3.utils.SharePreferencesUtil;
import cn.com.pajx.pajx_visitor_v3.utils.ToastUtil;

/**
 * 主页面
 */
@SuppressLint("NonConstantResourceId")
public class MainActivity extends BaseMvpActivity<LoadDataPresenterImpl> implements AlarmTaskReceiver.AlarmTaskListener, ScanCallBack {

    @BindView(R.id.tv_order_today)
    TextView tvOrderToday;
    @BindView(R.id.tv_visitor_today)
    TextView tvVisitorToday;

    private VisitorInfoFragment visitorInfoFragment;
    private Intent intent;
    //人脸识别相关
    private String order_id, visitor_info;
    private long exitTime = 0;//退出App
    //定时任务的广播
    private AlarmTaskReceiver alarmTaskReceiver;

    @Override
    public void onResume() {
        //初始化扫码的工具
        initScanTool();
        //检测是否是第一次安装
        checkIsFirstInstall();
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        releaseScanTool();
    }

    @Override
    protected void onStart() {
        super.onStart();
        //注册定时任务广播
        registerAlarmReceiver();
    }

    @Override
    protected boolean isTimerStart() {
        return false;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected LoadDataPresenterImpl initPresenter() {
        return new LoadDataPresenterImpl();
    }

    @Override
    protected boolean isBackView() {
        return false;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        //初始化定时任务的service
        initAlarmService();
        //初始化设置的View
        initSettingView();
    }

    /**
     * 初始化扫码工具
     */
    private void initScanTool() {
        try {
            ScanTool.GET.initSerial(this, "/dev/ttyS7", 115200);
            ScanTool.GET.setScanCallBack(this);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 初始化定时数据的service
     */
    private void initAlarmService() {
        //开启服务执行定时任务
        Intent intent = new Intent(this, AlarmService.class);
        startService(intent);
    }

    /**
     * 初始化设置的View
     */
    private void initSettingView() {
        //今日预约及今日拜访
        Typeface fontFace = Typeface.createFromAsset(getAssets(), "DIN Alternate Bold.ttf");
        tvOrderToday.setTypeface(fontFace);
        tvVisitorToday.setTypeface(fontFace);
        View view = setViewStubLayout(viewStubRight, R.layout.view_stub_main);
        FrameLayout viewHistory = view.findViewById(R.id.view_stub_history);
        FrameLayout viewSetting = view.findViewById(R.id.view_stub_setting);
        viewHistory.setOnClickListener(view1 -> startActivity(new Intent(mContext, QueryHistoryActivity.class)));
        viewSetting.setOnClickListener(view2 -> startActivity(new Intent(mContext, SettingActivity.class)));
    }

    /**
     * 检测是否是第一次安装
     */
    private void checkIsFirstInstall() {
        boolean isFirstInstall = SharePreferencesUtil.getInstance().getBoolean(AppConstant.FIRST_INSTALL, true);
        if (isFirstInstall) {
            BindSchoolFragment bindSchoolFragment = BindSchoolFragment.newInstance(false);
            bindSchoolFragment.show(getSupportFragmentManager(), "bindSchoolFragment");
        }
    }

    /**
     * 注册定时任务广播
     */
    private void registerAlarmReceiver() {
        //注册广播
        if (alarmTaskReceiver == null) {
            alarmTaskReceiver = new AlarmTaskReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction("com.pajx.alarm.RECEIVER");
            registerReceiver(alarmTaskReceiver, filter);
            //设置监听
            alarmTaskReceiver.setOnAlarmTaskListener(this);
        }
    }

    /**
     * 释放扫码工具
     */
    private void releaseScanTool() {
        try {
            ScanTool.GET.release();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取当前已预约及已拜访数量
     */
    private void loadTodayCount() {
        boolean isFirst = SharePreferencesUtil.getInstance().getBoolean(AppConstant.FIRST_INSTALL, true);
        if (isFirst) return;
        mPresenter.loadData(Api.VISITE_ORDER_COUNT, new LinkedHashMap<>(), "VISITE_ORDER_COUNT", "");
    }

    //两次返回 退出
    public void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            ToastUtil.toast("再按一次退出程序");
            exitTime = System.currentTimeMillis();
        } else {
            ActivityManagerUtil.getInstant().exitApp(MainActivity.this);
        }
    }

    @Override
    protected boolean isExcute() {
        return false;
    }

    @OnClick({R.id.view_face, R.id.view_scan, R.id.view_query_order, R.id.view_new_visite})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.view_face://人脸识别
                intent = new Intent(mContext, FaceNIRActivity.class);
                startActivity(intent);
                break;
            case R.id.view_scan://扫码出门
                intent = new Intent(mContext, ScanCodeActivity.class);
                startActivity(intent);
                break;
            case R.id.view_query_order://预约查询
                intent = new Intent(mContext, QueryOrderActivity.class);
                startActivity(intent);
                break;
            case R.id.view_new_visite://新建拜访
                intent = new Intent(mContext, NewVisiteActivity.class);
                startActivity(intent);
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + view.getId());
        }

    }

    @Override
    public void executeAlarmTask() {
        LogUtils.e("5min执行定时任务");
        loadTodayCount();
    }

    //监听返回键
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onNetChange(boolean netStatus) {
        super.onNetChange(netStatus);
        //防止自启动时系统网络模块未启动，联网后重新刷新数据
        if (netStatus) {
            loadTodayCount();
        }
    }

    private List<MainVisiteBean> visiteBeans;

    @Override
    public void onSuccess(String data, String aes_key, String message, int code, String tag) {
        super.onSuccess(data, aes_key, message, code, tag);
        try {
            JSONObject jsonObject = new JSONObject(data);
            int order_count = jsonObject.getInt("today_visit");
            int visitor_count = jsonObject.getInt("today_already");
            tvOrderToday.setText(String.valueOf(order_count));
            tvVisitorToday.setText(String.valueOf(visitor_count));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        //反注册定时任务广播
        if (alarmTaskReceiver != null && mContext != null) {
            mContext.unregisterReceiver(alarmTaskReceiver);
        }
    }

    @Override
    public void onScanCallBack(String data) {
        LogUtils.e("scanData=" + data);
        String vis_id = loadVisiteId(data);
        if (visitorInfoFragment == null && getSupportFragmentManager() != null && !TextUtils.isEmpty(vis_id)) {
            visitorInfoFragment = VisitorInfoFragment.newInstance(vis_id, AppConstant.VISITE_END);
            visitorInfoFragment.show(getSupportFragmentManager(), "visitorInfoFragment");
            visitorInfoFragment = null;
        }
    }

    @Override
    public void onInitScan(boolean isSuccess) {
        ScanCallBack.super.onInitScan(isSuccess);
        ScanTool.GET.playSound(true);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusMessage(EventMessage bean) {
        switch (bean.getMessage()) {
            case AppConstant.NEW_VISITE://新建拜访
            case AppConstant.VISITE_END://结束拜访
                loadTodayCount();
                break;
            case AppConstant.CHANGE_SCHOOL://切换学校
            case AppConstant.UNBIND_SCHOOL://解绑成功
                tvHeadTitle.setText(loadHeadTitle());
                break;
        }
    }
}
